import { BaseModel } from "../../models/base";

// index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPickerModal: false,
    filteredList: [],
    array: [ ],
    credit: false,
    transferList: [],
    totalAmount: 0,
    bankTransferList : [],
    creditData:{
      creaditAmount: 0,
      useAmountL: 0,
      availableAmount: 0,
      schedule: '0%',
      totalAmount: 0,
    },
    form: {
      advertiserId: 0,
      totalAmount: '',
      amount: '',
      creditAmount: '',
      remark: ''
    },
    availableUseAmount: 0,
    checked: '',
    index: 0,
    amount: 0,
    type: 1,
    showVal: false,
    itemList: [],
    advertiserAmountList:[],
    transferAdvertiserAmountList: [],
    returnCreditForm: {
      advertiserId: '',
      amount: '',
      remark: ''
    }
  },


  cucelTotalAmount() {
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  // 校验当前用户是否可以使用信用额度
  validateCredit() {
    let base = new BaseModel(), that = this
    base.validateCredit().then(res => {
      if (res.code == 200) {
        let data = res.data
        that.setData({credit: data})
      }
    })
  },
  getCreditData(advertiserId) {
    let baseModel = new BaseModel(), that = this;
    baseModel.getCreditAmount(advertiserId).then(res => {
      if (res.code == 200) {
        let data = res.data, credit = that.data.credit, availableUseAmount = data.availableUseAmount
        if (data && data != null) {
          if (credit) {
            credit = data.availableAmount > 0
          }
        that.setData({
          'creditData': data,
          'credit': credit,
          'availableUseAmount': availableUseAmount
        })

      }
        that.cucelTotalAmount()
      }
    })
  },

  /**
   *  
   * @param {*} advertiserId 
   */
  getAllAdvertiserAmount(advertiserId) {
    let baseModel = new BaseModel(), that = this;
    baseModel.getAllAdvertiserAvailableAmount(advertiserId).then(res => {
      if (res.code == 200) {
        let data = res.data, list = data.filter(item => item.advertiserId != advertiserId);
        list.map(item => {
            item.disabled = true;
            item.amount = 0
        })
        console.log(list)
        that.setData({advertiserAmountList: list})

        that.cucelTotalAmount()
      }
    })
  },

  checkbox(e) {
    let value = e.detail.value, requests = [],  list = this.data.advertiserAmountList, number = [],
    type = this.data.type;
    value.map(item => {
      let obj = {};
      obj.advertiserId = item;
      requests.push(obj)
      number.push(parseInt(item))
    })

    list.map(item => {
      if (number.indexOf(item.advertiserId) > -1) {
        item.disabled = false
      }
    })

    let object = {};
    if (type == 1) {
      object = {
        'form.requests': requests,
        'advertiserAmountList': list
      }
    } else {
      object = {
        'returnCreditForm.requests': requests,
        'advertiserAmountList': list
      }
    }

    this.setData(object)
  },
  changeBut(e){
    let index = e.detail.value,
    array = this.data.array, that = this;
    let one = array[index];
    let advertiserId = one.name, id = one.id, checkedAdvertiser = one.advertiserName + "(" + advertiserId + ")";
    // 获取广告主可用的金额信息
    if (advertiserId != null) {
      console.log(advertiserId)
      that.getAdvertiserAvailableAmount(advertiserId)
      that.getAllAdvertiserAmount(advertiserId)
      that.getCreditData(advertiserId)
    }
    that.setData({
      'form.advertiserId': id,
      'form.account': advertiserId,
      'returnCreditForm.advertiserId': advertiserId,
      'checked': checkedAdvertiser
    })
  },

  getAdvertiserAvailableAmount(advertiserId) {
    let base = new BaseModel(), that = this, form = this.form;
    base.getAdvertiserAmount(advertiserId).then(res => {
      if (res.code == 200) {
        let data = res.data,
        totalAmount = data.totalAmount;
        that.setData({
        'form.totalAmount': totalAmount})
      }
    })
  },

  goTransfer() {
    wx.navigateTo({
      url: '/pages/transfer/index',
    })
  },

  showPicker: function () {
    this.setData({
      showPickerModal: true,
      filteredList: this.data.array // 重置过滤列表
    });
  },

  hidePicker: function () {
    this.setData({
      showPickerModal: false
    });
  },

  onSearchInput: function (e) {
    const keyword = e.detail.value;
    const filteredList = this.data.array.filter(item => item.remark.includes(keyword));
    this.setData({
      filteredList: filteredList
    });
  },

  selectItem: function (e) {
    const item = e.currentTarget.dataset.item;
    let array = this.data.array, that = this;
    let one = item,
    form = that.data.form,
    returnCreditForm = that.data.returnCreditForm;
    let advertiserId = one.name, id = one.id;
    let checkedAdvertiser = one.advertiserName + "(" + advertiserId + ")";
    // 获取广告主可用的金额信息
    if (advertiserId != null) {
      console.log(advertiserId)
      that.getAdvertiserAvailableAmount(advertiserId)
      that.getAllAdvertiserAmount(advertiserId)
      that.getCreditData(advertiserId)
    }
    // that.setData({
    //   'form.advertiserId': id,
    //   'form.account': advertiserId,
    //   'returnCreditForm.advertiserId': advertiserId,
    //   'checked': checkedAdvertiser
    // })
    form.advertiserId = id;
    form.account = advertiserId;
    returnCreditForm.advertiserId = advertiserId;
    that.setData({
      form, returnCreditForm,
      checked: checkedAdvertiser,
      showPickerModal: false
    });
  },

  getAdvertiserList() {

    let base = new BaseModel(), that = this;
    base.getAdvertiserList().then(res => {
      if (res.code == 200) {
        let data = res.data, list = [], nameList = [];
        data.map(item => {
          let obj = item;
          obj.remark = item.advertiserName + "(" + item.name + ")";
          list.push(obj);
        })
        that.setData({array: list,
          filteredList: list
        })
        data.map(item => {
          nameList.push(item.name)
        })

        that.setData({ 
          itemList: nameList
        })
        wx.hideLoading()
      }
    })
  },

  getBankTransferList() {
    let base = new BaseModel(), that = this;
    base.getBankTransferList().then(res => {
      if (res.code == 200) {
        let data = res.data;
        that.setData({transferList: data})
      }
    })
  },
  inputTag(e) {
    var that = this, value = e.detail.value, index = e.currentTarget.dataset.index;
    that.setDataValue(index, value)
   // this.cucelAmount()
  },

  inputTagCredit(e) {
    let value = e.detail.value
    this.setData({
      'form.creditAmount': value
    })
  },

  inputTagReturnCredit(e) {
    let value = e.detail.value
    this.setData({
      'returnCreditForm.amount': value
    })
  },

  setDataValue(index, value) {
    let data = {}, type = this.data.type;
    if (type == 1) {
      data = {
        [`advertiserAmountList[${index }].amount`]: value,
        [`form.requests[${index}].amount`]: value
      }
    } else {
      data = {
        [`advertiserAmountList[${index }].amount`]: value,
        [`returnCreditForm.requests[${index}].amount`]: value
      }
    }

    this.setData(data);

  },

  inputRemark(e) {
    let remark = e.detail.value
    this.setData({
      'form.remark': remark
    })
  },

  inputReturnRemark(e) {
    let remark = e.detail.value
    this.setData({
      'returnCreditForm.remark': remark
    })
  },

  inputTotalAmount(e) {
    let value = e.detail.value, showVal = value - this.data.availableUseAmount > 0
    this.setData({
      'form.amount': value,
      'showVal': showVal
    })
  },

  submitReturnCredit() {
    let baseModel = new BaseModel();
    wx.showLoading({
      title: '处理中...',
    })
    baseModel.submitReturnCredit(this.data.returnCreditForm)
    .then(res => {
      wx.hideLoading();
      wx.showToast({
        title: res.message,
        icon: "none",
        duration: 2000
      })

      if (res.code == 200) {
        that.refresh()
      }
    })
  },

  submit(){
    wx.showLoading({
      title: '处理中...',
    });
    
    let baseModel = new BaseModel(), that = this;
    baseModel.topUp(this.data.form).then(res => {
      wx.hideLoading();
      wx.showToast({
        title: res.message,
        icon: "none",
        duration: 2000
      })
      
      if (res.code == 200) {
        that.refresh()
      }
    })
  },

  refresh() {
    let form = {
      advertiserId: 0,
      totalAmount: '',
      amount: '',
      creditAmount: '',
      remark: ''
    }, 
    returnCreditForm = {
      advertiserId: '',
      amount: '',
      remark: ''
    }

    this.setData({
      'form': form,
      'returnCreditForm': returnCreditForm
    })
  },

  inputTagAmount(e) {
    let value = e.detail.value
    this.setData({
      'form.totalAmount': value
    })

    //this.cucelAmount()
  },

  cucelAmount () {
    let totalAmount = this.data.totalAmount, creditAmount = this.data.creditAmount,
    amount = totalAmount* 1 + creditAmount *1;
    this.setData({
      'form.amount': amount
    })
  },

  butTab(e){
    var that = this,
    type = e.currentTarget.dataset.type;
    that.setData({
      type
    })
  },


  money(val) {
    val = val.replace(/[^\d.]/g, '')
    val = val.replace(/^\./g, '')
    val = val.replace(/\.{2,}/g, '.')
    val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    val = val.replace(/^0{1,}/g,'');
    return val;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    wx.showLoading({
      title: '数据正在加载中。。。',
    })
    setTimeout(function () {
      that.getAdvertiserList()
      that.getBankTransferList()
      that.validateCredit()
    }, 1500
    )
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
